package com.OnTimeTeam.OnTime;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.widget.TextView;
import android.widget.Toast;

public class FindCurrentLocationAsyncTask extends AsyncTask<String, Void, Boolean> {

	private Boolean addIsOK;
    ProgressDialog progressDialog;
    private Dialog dialog;
    private SmartAlarmFeatures af;
    private String location;
    private String path;
	private SetSmart host;
	private String currentLocation;
	private GPSManager gps;
	
	public FindCurrentLocationAsyncTask(SetSmart host,Dialog dialog, String location, SmartAlarmFeatures af, String path){
		this.host = host;
		this.dialog = dialog;
		this.af = af;
		this.location = location;
		this.path = path;
		this.currentLocation = null;
	}
	
    protected Boolean doInBackground(String... params) {//In Background

		addIsOK = true;

		// check if GPS enabled
		if(gps.canGetLocation()){
			
			currentLocation = gps.getLocationAddress();
			if(currentLocation.equals(""))
				addIsOK = false;
		} 
		else
			addIsOK = false;

		
    	return addIsOK;
    }      

    protected void onPreExecute() {//Before
    	super.onPreExecute();
    	
    	gps = new GPSManager(host.getApplicationContext());
    	
    	progressDialog = ProgressDialog.show(host, host.getResources().getString(R.string.searchingCurrentLocation), host.getResources().getString(R.string.pleaseWait));
    
    	
    }
    
    protected void onPostExecute(Boolean result) {//After

    	progressDialog.dismiss();
    	
    	if(result) {

			if(location.equals("origin")) {
				af.setOrigin(currentLocation);
				AddressAutoCompletionIO.addNewAddress(path + "/addresses.xml", af.getOrigin());
			}
			else {
				af.setDest(currentLocation);
				AddressAutoCompletionIO.addNewAddress(path + "/addresses.xml", af.getDest());
			}
    		
     		host.ADDRESSES = AddressAutoCompletionIO.getAllAddresses(path + "/addresses.xml");
			host.smartListAdapter.notifyDataSetChanged();
			
			dialog.dismiss();
        }
        else
        	host.showSettingsAlert();


    }



    protected void onProgressUpdate(Void... values) {
    	
    	
    }
}

